<template>
  <div class="failed-page h-100 d-flex align-items-center justify-content-center">
    <el-empty class="p-0">
      <template #description>
        <div class="text-danger">访问异常</div>
        <div v-if="errCode">
          <small class="text-danger">
            {{ errCode }}
          </small>
        </div>
      </template>
      <div class="text-secondary border p-2 py-3 rounded-1">
        <div v-if="errCode === 'CLIENT_TIME_FAILED'"
             class="mb-1 text-info">本地时间与服务器时间不一致，请检查本地时间是否于网络同步！</div>
        <div v-if="errCode === 'UNKNOW_FAILED'"
             class="mb-1 text-info">
          未知的问题，请联系管理员<span v-if="errMsg">，并将提供本页信息</span>！
          <div v-if="errMsg">{{ errMsg }}</div>
        </div>
        <div class="mb-2">请稍后访问或尝试</div>
        <el-button type="primary"
                   @click.stop="doRefreshPage">刷新页面</el-button>
      </div>
    </el-empty>
  </div>
</template>

<script lang="ts">
  import { Component, Vue } from "@some21/vue-class-decorator";
  import qs from "qs";
  import { CURRENT_BASE_URL, getCacheId } from "@/framework/utilities";

  @Component({
    name: "failed-page",
  })
  export default class extends Vue {
    errCode: string;
    errMsg: string;

    created() {
      if (location.search && location.search.length) {
        const searchParams = qs.parse(location.search.substring(1));
        this.errCode = searchParams.errCode as string;
        this.errMsg = searchParams.errMsg as string;
      }
      window.addEventListener("keydown", this.onKeyDown, false);
    }
    async onKeyDown(e) {
      // 禁止 F5, ctrl+R 刷新操作
      if (e.keyCode === 116 || (e.ctrlKey && e.keyCode === 82)) {
        e.preventDefault(); // 阻止系统默认刷新动作。
        e.stopPropagation();
        e.cancelBubble = true;
        e.returnValue = false;
        this.doRefreshPage();
        return false;
      }
    }
    doRefreshPage() {
      let { returnUrl } = qs.parse(location.search.substring(1));
      if (!returnUrl) {
        returnUrl = CURRENT_BASE_URL;
      }
      const url = new URL(returnUrl as string);
      url.searchParams.delete("ts");
      url.searchParams.append("ts", getCacheId());
      location.replace(url);
    }
    beforeDestroy() {
      window.removeEventListener("keydown", this.onKeyDown);
    }
  }
</script>

<style lang="scss" scoped></style>
